#!/bin/bash

# MySQL MCP Server 测试客户端（增强版）

SERVER_URL=${1:-http://localhost:8080}
MODE=${2:-http}

echo "=== MySQL MCP Server 测试客户端（增强版）==="
echo "服务器地址: $SERVER_URL"
echo "模式: $MODE"
echo

# 检查服务器是否可访问
check_server() {
    echo "1. 检查服务器连接..."
    
    # 首先检查健康状态端点
    echo "   检查健康状态端点..."
    health_response=$(curl -s "$SERVER_URL/health" 2>/dev/null)
    if [ $? -eq 0 ]; then
        echo "   ✓ 健康检查响应: $health_response"
    else
        echo "   ⚠ 健康检查端点不可用"
    fi
    
    if [ "$MODE" = "http" ]; then
        endpoint="$SERVER_URL/mcp"
    else
        endpoint="$SERVER_URL/message"
    fi
    
    echo "   检查主服务端点 ($endpoint)..."
    if ! curl -s --fail "$endpoint" > /dev/null 2>&1; then
        echo "   ❌ 无法连接到服务器 $endpoint"
        echo "   请确保服务器正在运行"
        exit 1
    fi
    echo "   ✓ 主服务端点连接正常"
    echo
}

# HTTP模式测试
test_http() {
    local endpoint="$SERVER_URL/mcp"
    echo "2. 使用HTTP模式测试 ($endpoint)"
    echo
    
    echo "   测试1: 初始化连接..."
    response=$(curl -s -X POST "$endpoint" \
        -H "Content-Type: application/json" \
        -d '{
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "protocolVersion": "2024-11-05",
                "capabilities": {"tools": {}},
                "clientInfo": {"name": "test-client", "version": "1.0.0"}
            }
        }' 2>/dev/null)
    
    if [ $? -eq 0 ] && [ -n "$response" ]; then
        echo "   ✓ 初始化成功"
        echo "   响应: $(echo "$response" | jq -c . 2>/dev/null || echo "$response")"
    else
        echo "   ❌ 初始化失败"
        return 1
    fi
    echo
    
    echo "   测试2: 获取工具列表..."
    response=$(curl -s -X POST "$endpoint" \
        -H "Content-Type: application/json" \
        -d '{
            "jsonrpc": "2.0",
            "id": 2,
            "method": "tools/list"
        }' 2>/dev/null)
    
    if [ $? -eq 0 ] && [ -n "$response" ]; then
        echo "   ✓ 获取工具列表成功"
        echo "   工具数量: $(echo "$response" | jq '.result.tools | length' 2>/dev/null || echo "未知")"
    else
        echo "   ❌ 获取工具列表失败"
        return 1
    fi
    echo
    
    echo "   测试3: 执行简单查询..."
    response=$(curl -s -X POST "$endpoint" \
        -H "Content-Type: application/json" \
        -d '{
            "jsonrpc": "2.0",
            "id": 3,
            "method": "tools/call",
            "params": {
                "name": "execute_query",
                "arguments": {
                    "query": "SELECT 1 as test_value, NOW() as current_time"
                }
            }
        }' 2>/dev/null)
    
    if [ $? -eq 0 ] && [ -n "$response" ]; then
        echo "   ✓ 查询执行成功"
        echo "   响应: $(echo "$response" | jq -c . 2>/dev/null || echo "$response")"
    else
        echo "   ❌ 查询执行失败"
        return 1
    fi
    echo
}

# SSE模式测试
test_sse() {
    local sse_endpoint="$SERVER_URL/sse"
    local message_endpoint="$SERVER_URL/message"
    
    echo "2. 使用SSE模式测试"
    echo "   SSE端点: $sse_endpoint"
    echo "   消息端点: $message_endpoint"
    echo
    
    echo "   测试1: 检查SSE端点..."
    if ! curl -s --fail "$sse_endpoint" > /dev/null 2>&1; then
        echo "   ❌ SSE端点不可访问"
        return 1
    fi
    echo "   ✓ SSE端点可访问"
    echo
    
    echo "   测试2: 发送初始化消息..."
    response=$(curl -s -X POST "$message_endpoint" \
        -H "Content-Type: application/json" \
        -d '{
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "protocolVersion": "2024-11-05",
                "capabilities": {"tools": {}},
                "clientInfo": {"name": "test-client-sse", "version": "1.0.0"}
            }
        }' 2>/dev/null)
    
    if [ $? -eq 0 ] && [ -n "$response" ]; then
        echo "   ✓ 初始化消息发送成功"
        echo "   响应: $(echo "$response" | jq -c . 2>/dev/null || echo "$response")"
    else
        echo "   ❌ 初始化消息发送失败"
        return 1
    fi
    echo
    
    echo "   测试3: 获取工具列表..."
    response=$(curl -s -X POST "$message_endpoint" \
        -H "Content-Type: application/json" \
        -d '{
            "jsonrpc": "2.0",
            "id": 2,
            "method": "tools/list"
        }' 2>/dev/null)
    
    if [ $? -eq 0 ] && [ -n "$response" ]; then
        echo "   ✓ 工具列表获取成功"
        echo "   工具数量: $(echo "$response" | jq '.result.tools | length' 2>/dev/null || echo "未知")"
    else
        echo "   ❌ 工具列表获取失败"
        return 1
    fi
    echo
}

# 性能测试
performance_test() {
    echo "3. 简单性能测试..."
    
    if [ "$MODE" = "http" ]; then
        endpoint="$SERVER_URL/mcp"
        payload='{
            "jsonrpc": "2.0",
            "id": 999,
            "method": "tools/call",
            "params": {
                "name": "execute_query",
                "arguments": {
                    "query": "SELECT 1"
                }
            }
        }'
    else
        endpoint="$SERVER_URL/message"
        payload='{
            "jsonrpc": "2.0",
            "id": 999,
            "method": "tools/list"
        }'
    fi
    
    echo "   执行10次连续请求..."
    start_time=$(date +%s%N)
    
    for i in {1..10}; do
        curl -s -X POST "$endpoint" \
            -H "Content-Type: application/json" \
            -d "$payload" > /dev/null 2>&1
        
        if [ $? -ne 0 ]; then
            echo "   ❌ 请求 $i 失败"
            return 1
        fi
    done
    
    end_time=$(date +%s%N)
    duration=$((($end_time - $start_time) / 1000000))
    avg_time=$(($duration / 10))
    
    echo "   ✓ 性能测试完成"
    echo "   总耗时: ${duration}ms"
    echo "   平均响应时间: ${avg_time}ms"
    echo
}

# 运行测试
echo "开始测试..."
echo

check_server

case $MODE in
    "http")
        test_http && performance_test
        ;;
    "sse")
        test_sse && performance_test
        ;;
    *)
        echo "❌ 不支持的模式: $MODE"
        echo "支持的模式: http, sse"
        exit 1
        ;;
esac

echo "=== 测试完成 ==="
echo
echo "测试建议:"
echo "- 查看服务器日志以获取详细信息"
echo "- 使用健康检查端点监控服务状态: $SERVER_URL/health"
echo "- 在生产环境中启用HTTPS和认证"

# 显示使用帮助
show_help() {
    echo "MySQL MCP Server 测试客户端"
    echo
    echo "用法: $0 [服务器地址] [模式]"
    echo
    echo "参数:"
    echo "  服务器地址    服务器URL (默认: http://localhost:8080)"
    echo "  模式         测试模式: http 或 sse (默认: http)"
    echo
    echo "示例:"
    echo "  $0                                    # 测试本地HTTP模式"
    echo "  $0 http://localhost:8080 http         # 测试HTTP模式"
    echo "  $0 http://localhost:8080 sse          # 测试SSE模式"
    echo "  $0 http://remote-server:8080 http     # 测试远程服务器"
    echo
}

# 检查参数
if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    show_help
    exit 0
fi 